import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Form, Input, Button, Card, Radio } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import 'braft-editor/dist/index.css';
import BraftEditor from 'braft-editor';
import styles from '../Less/form.less';
const FormItem = Form.Item;
const { TextArea } = Input;
@connect(({ doc, loading }) => ({
  doc,
  loading: loading.effects['doc/fetchDetail'],
  submitting: loading.effects['doc/fetchUpdateDetail'],
}))
@Form.create()
class EditForm extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      // 创建一个空的editorState作为初始值
      editorState: BraftEditor.createEditorState('<p>Hello <b>World!</b></p>'), // 设置编辑器初始内容
      outputHTML: '<div></div>',
    };
  }

  componentDidMount() {
    const _this = this;
    const { dispatch, match, doc } = this.props;
    const { docDetail = {} } = doc;
    const { params } = match;
    dispatch({
      type: 'doc/fetchDetail',
      payload: params.id,
      callback(content) {
        this.setState({
          editorState: [...BraftEditor.createEditorState('')],
        });
      },
    });
  }

  setEditorContentAsync = content => {
    this.setState({
      editorState: BraftEditor.createEditorState(content),
    });
  };
  handleSubmit = e => {
    e.preventDefault();
    const { dispatch, form, doc } = this.props;
    const { docDetail = {} } = doc;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.id = docDetail.id;
        values.content = values.content.toHTML();
        dispatch({
          type: 'doc/fetchUpdateDetail',
          payload: values,
          callback() {
            router.push('/doclist/table-list');
          },
        });
      }
    });
  };
  componentWillUnmount() {
    this.isLivinig = false;
  }
  handleChange = editorState => {
    this.setState({
      editorState: editorState,
    });
  };
  setEditorContentAsync = () => {
    this.isLivinig &&
      this.setState({
        editorState: BraftEditor.createEditorState('<p>你好，<b>世界!</b><p>'),
      });
  };

  render() {
    const { doc, loading, submitting, form } = this.props;
    const { docDetail = {} } = doc;
    const { getFieldDecorator } = form;
    const { editorState } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };
    const myUploadFn = param => {
      const serverURL = '/lgjserve/singleupload';
      const xhr = new XMLHttpRequest();
      const fd = new FormData();

      const successFn = response => {
        // 假设服务端直接返回文件上传后的地址
        // 上传成功后调用param.success并传入上传后的文件地址
        let data = JSON.parse(xhr.responseText);
        console.log(data);
        param.success({
          url: data.data,
        });
      };

      const progressFn = event => {
        // 上传进度发生变化时调用param.progress
        param.progress((event.loaded / event.total) * 100);
      };

      const errorFn = response => {
        // 上传发生错误时调用param.error
        param.error({
          msg: 'unable to upload.',
        });
      };

      xhr.upload.addEventListener('progress', progressFn, false);
      xhr.addEventListener('load', successFn, false);
      xhr.addEventListener('error', errorFn, false);
      xhr.addEventListener('abort', errorFn, false);

      fd.append('picture', param.file);
      xhr.open('POST', serverURL, true);
      xhr.send(fd);
    };
    return (
      <PageHeaderWrapper>
        <Card bordered={false} loading={loading}>
          <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
            <FormItem {...formItemLayout} label="标题">
              {getFieldDecorator('title', {
                rules: [{ required: true, message: '请输入标题' }],
                initialValue: docDetail.title,
              })(<Input placeholder="输入标题" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="类别">
              {getFieldDecorator('parent_id', {
                rules: [{ required: true, message: '请选择类别' }],
                initialValue: docDetail.parent_id,
              })(
                <Radio.Group>
                  <Radio value={1}>用户</Radio>
                  <Radio value={2}>商户</Radio>
                </Radio.Group>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="内容">
              {getFieldDecorator('content', {
                //BraftEditor引用后就可以使用
                initialValue: BraftEditor.createEditorState(docDetail.content),
              })(
                <BraftEditor
                  value={editorState}
                  className={styles.myEditor}
                  placeholder="请输入内容"
                  onChange={this.handleChange}
                  media={{
                    uploadFn: myUploadFn,
                  }}
                />
              )}
            </FormItem>

            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" htmlType="submit" loading={submitting}>
                <FormattedMessage id="form.submit" />
              </Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default EditForm;
